package com.nacos.controller;

import com.dubbo.service.api.Service2Api;
import com.nacos.dubbo.api.Service1Api;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@RestController
public class NacosConsumerController {
    //服务提供方的地址
    @Value("${provider.address}")
    private String address;
    private String serviceId="nacos-restful-provider";
    @org.apache.dubbo.config.annotation.Reference
    private Service2Api service2Api;
    @Autowired
    private ConfigurableApplicationContext applicationContext;
    @GetMapping("/service")
    public String service(){
        RestTemplate restTemplate=new RestTemplate();
        String forObject = restTemplate.getForObject(address + "/provider/Server", String.class);
        return "consumer:"+forObject;
    }

    /**
     * 通过负载均衡算法发现地址，流程是从服务发现中心拿到nacos-restful-provider列表
     * 通过负载均衡算法获取一个服务地址
     */
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/service1")
    public String service1(){
        RestTemplate restTemplate=new RestTemplate();
        ServiceInstance serviceInstance = loadBalancerClient.choose(serviceId);//根据服务名称找到服务实例
        URI uri = serviceInstance.getUri();//获取一个http://ip:端口号
        String forObject = restTemplate.getForObject(uri + "/provider/Server", String.class);
        System.out.println("consumer:"+forObject);
        return "consumer:"+forObject;
    }


    @GetMapping("/service2")
    public String service2(){
        String s = service2Api.dubboService2();
        return "consumer dubbo invoke |" +s;
    }
    @Reference
    private Service1Api service1Api;
    @GetMapping("/service3")
    public String Service3(){
        String s = service1Api.service1();
        return "service1调用service2"+s;
    }

    @GetMapping("/getConfig")
    public String getConfig(){
        String property = applicationContext.getEnvironment().getProperty("common.name")+applicationContext.getEnvironment().getProperty("common.addr");
        return property;
    }
}
